#include <iostream>
#include "tcpsocket.h"

#include <spdlog/spdlog.h>

using std::cout;
using std::endl;

#define READ_TYPE   2

int main()
{
    TcpSocket::startup();

    spdlog::set_level(spdlog::level::debug);

#if READ_TYPE == 1
    TcpSocket socket;
    auto callback = [&]{
        try {
            auto str = socket.readAll();
            spdlog::debug("read data: {}", str);
        } catch(...) {
            spdlog::debug("callback throw");
        }
    };
    socket.registerReadyReadSig(callback);

    bool f = socket.connectToHost("127.0.0.1", 5188);
    spdlog::debug("connect flag : {}", f);
#endif

    while(1) {
#if READ_TYPE != 1
        TcpSocket socket;
        bool f = socket.connectToHost("127.0.0.1", 5188);
        spdlog::debug("connect flag : {}", f);
#endif

        std::cout << "input send data:" << std::flush;
        std::string str;
        if(!getline(std::cin, str)) break;
        if(str.empty()) continue;

        int sendSize = socket.write(str);
        if(sendSize != (int)str.size()) spdlog::debug("send error {} {}", sendSize, str.size());
        if(sendSize < 0) spdlog::debug("remote close");

#if READ_TYPE == 2
        if(!socket.waitForReadyRead(100)) {
            spdlog::debug("wait data failed");
            continue;
        }
        str = socket.readAll();
        spdlog::debug("read data: {}\n", str);
#endif

#if READ_TYPE == 3
        while(!socket.isReadyRead()) { }
        str = socket.readAll();
        spdlog::debug("read data: {}\n", str);
#endif

#if READ_TYPE == 4
        socket.waitForReadyRead(10);
        do {
            str = socket.read(1);
            std::cout << str;
        }while(!str.empty());
        std::cout << std::endl;
#endif

        std::cout << std::endl;
    }

    TcpSocket::cleanup();

    return 0;
}
